package me.lc.linklink.core;

import java.util.Timer;
import java.util.TimerTask;

import com.wiyun.engine.nodes.Director;
import com.wiyun.game.WiGame;

import me.lc.linklink.entity.StageInfo;
import me.lc.linklink.layer.GameLayer;
import me.lc.linklink.sprite.ComboBlock;
import me.lc.linklink.sprite.ProcessBlock;
import me.lc.linklink.util.AudioHelper;

/**
 * 负责游戏进程控制
 * 
 * @author Administrator
 * 
 */
public class GameManager {
	public static GameManager instance = new GameManager();

	/**
	 * 每次消除的基础分数，连续combo将翻倍，最高为基础分数的16倍
	 */
	private static final int baseScore = 10;

	public boolean isTimeAdded() {
		return isTimeAdded;
	}

	public int getCurrentGameSecond() {
		return currentGameSecond;
	}

	public int getStageScore() {
		return stageScore;
	}

	public int getLongCombo() {
		return longCombo;
	}

	public boolean isPaused() {
		return isPaused;
	}

	private int timeGameClearCount;

	public int getTimeGameClearCount() {
		return timeGameClearCount;
	}

	private boolean isPaused = true;

	private boolean isTimeAdded = false;
	private int totalGameSecond;
	private int currentGameSecond;
	private int stageScore;
	private int longCombo;
	private int currentCombo;
	private int coupleCount;
	private int clearCount;
	private ComboBlock comboBlock;
	private ProcessBlock processBlock;

	public GameType CurrentGameType;
	public GameArrangeType ArrangeType;

	private boolean isLinked = false;
	private Object comboJudgeLock = new Object();
	private int comboTimeoutCount = GameSystem.ComboTimeout;
	private GameLayer gameLayer;

	private Timer gameTimer;

	private GameManager() {

	}

	public void initNewGame(ProcessBlock block, int stageIndex,
			GameLayer gameLayer, GameType currType) {
		this.gameLayer = gameLayer;
		StageInfo stageInfo = StageManager.instance.stageInfos.get(stageIndex);
		this.CurrentGameType = currType;
		this.ArrangeType = stageInfo.getArrType();
		coupleCount = (GameSystem.GameColumns * GameSystem.GameRows) / 2;
		clearCount = 0;
		isTimeAdded = false;

		if (CurrentGameType == GameType.Normal) {
			totalGameSecond = stageInfo.getTotalTime();
			currentGameSecond = stageInfo.getTotalTime();
		} else {
			totalGameSecond = 99;
			currentGameSecond = 99;
			isTimeAdded = true;
			timeGameClearCount = 0;
		}

		currentCombo = -1;
		stageScore = 0;
		longCombo = 0;
		processBlock = block;
		processBlock.initProcessBlock(totalGameSecond);
		isPaused = true;

	}

	public void pauseGame() {
		isPaused = true;
	}

	public void resumeGame() {
		isPaused = false;
	}

	public void quitGame() {
		if (gameTimer != null) {
			gameTimer.cancel();
			gameTimer = null;
		}
		isPaused = true;
	}

	public void startGame() {
		if (gameTimer != null) {
			gameTimer.cancel();
			gameTimer = null;
		}
		gameTimer = new Timer();
		GameClockTask task = new GameClockTask();
		gameTimer.schedule(task, 1000, 1000);
		isPaused = false;
	}

	public void failedGame() {
		try {
			if (gameTimer != null) {
				gameTimer.cancel();
				gameTimer = null;
			}
		} catch (Exception e) {

		}
		if (CurrentGameType == GameType.Normal) {
			AudioHelper.lose();
			gameLayer.showLose();
			isPaused = true;
			System.out.println("你输了");
		} else {
			AudioHelper.win();
			gameLayer.showWin();
			isPaused = true;
			System.out.println("争分夺秒时间到");
		}
	}

	public void finishGame() {
		if (gameTimer != null) {
			gameTimer.cancel();
			gameTimer = null;
		}
		AudioHelper.win();
		gameLayer.showWin();
		isPaused = true;
		System.out.println("你赢了");
		System.out.println(stageScore);
	}

	/**
	 * 消除元素
	 * 
	 * @return 是否结束
	 */
	public boolean clearCouple() {
		timeGameClearCount++;
		clearCount++;
		currentCombo++;
		AudioHelper.clearItem();
		if (currentCombo >= 8) {
			WiGame.unlockAchievement("ef7d9e008a0a9520");
		}
		if (currentCombo >= 25) {
			WiGame.unlockAchievement("468e7d50444135fe");
		}

		System.out.println("combo:" + currentCombo);
		if (currentCombo > longCombo) {
			longCombo = currentCombo;
		}
		if (currentCombo > 1) {
			comboBlock.showCombo(currentCombo);
		}
		int temp = currentCombo;
		if (temp > 4) {
			temp = 4;
		}
		int awardBase = (int) Math.pow(2, temp);
		stageScore += baseScore * awardBase;

		synchronized (comboJudgeLock) {
			isLinked = true;
		}
		if (clearCount >= coupleCount) {
			if (CurrentGameType == GameType.Normal) {
				finishGame();
				return true;
			} else {
				// 争分夺秒连接完毕了，重新生成界面图
				GameMap.gen(gameLayer, GameSystem.Time_Stage_Index);
				clearCount = 0;
				gameLayer.forceComboBlock();
			}
		}
		return false;

	}

	public void comboBreak() {
		currentCombo = -1;
	}

	/**
	 * 增加15秒时间
	 */
	public void addTime() {
		isTimeAdded = true;
		currentGameSecond += 15;
		if (currentGameSecond > totalGameSecond) {
			currentGameSecond = totalGameSecond;
		}
		processBlock.updateProcess(currentGameSecond);
	}

	public void setComboBlock(ComboBlock comboBlock) {
		this.comboBlock = comboBlock;
	}

	class GameClockTask extends TimerTask {
		@Override
		public void run() {
			System.out.println("GameClockTask");
			if (currentGameSecond > 0 && !isPaused) {
				System.out.println("检查combo时间");
				System.out.println("isLinked=" + isLinked);
				synchronized (comboJudgeLock) {
					if (isLinked) {
						comboTimeoutCount = GameSystem.ComboTimeout;
						isLinked = false;
					} else {
						if (comboTimeoutCount > 0) {
							comboTimeoutCount--;
						} else {
							comboBreak();
						}
					}
				}

				currentGameSecond--;
				Director.getInstance().runOnGLThread(new Runnable() {
					@Override
					public void run() {
						processBlock.updateProcess(currentGameSecond);
						if (currentGameSecond <= 0) {
							failedGame();
						}
					}
				});
			}
		}
	}
}
